/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package presentation;

import entity.Commande;
import entity.LignCmd;
import entity.LignCmdPK;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.LinkedList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.util.Collection;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.table.TableModel;

/**
 *
 * @author Khalid
 */
public class CommandeDetailForm extends JPanel {

    /**
     * Creates new form CommandeDetailForm
     */
    private final static double PARPA = 7.3;
    private final static double LOURDI = 0.62;

    private entity.Commande currentCommande;
    //private javax.persistence.EntityManager entityManager;
    private Collection<entity.LignCmd> ls;

    public CommandeDetailForm(entity.Commande c) {
//        EntityManager entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("gestionPU").createEntityManager();
//        this.currentCommande = entityManager.find(entity.Commande.class, 1);
        initComponents();
        //entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("gestionPU").createEntityManager();
        if (!Beans.isDesignTime()) {
            gestionPUEntityManager.getTransaction().begin();
        }
        this.currentCommande = c;
        //this.currentCommande.setLignCmdCollection((List)new LinkedList<LignCmd>());
        //initComponents();
        this.enableComponent();
        this.createJtable();
        if (currentCommande == null) {
            this.currentCommande = new Commande();
            gestionPUEntityManager.persist(this.currentCommande);
            cmbClient.setSelectedIndex(-1);

        } else {
            currentCommande = gestionPUEntityManager.find(Commande.class, currentCommande.getId());
            fillForm(this.currentCommande);
        }
//        if (jTable1.getSelectedRows().length == 0) {
            cmbPdt.setSelectedIndex(-1);
//        }

        lblMsg.setVisible(false);
        lblMsg1.setVisible(false);

    }

    void enableComponent() {
        boolean test = this.getCurrentCommande() == null;
        cmbClient.setEnabled(test);
        jdate.setEnabled(test);
        txtBenefice.setEnabled(test);
        txtCredit.setEnabled(test);
        txtTotal.setEnabled(test);
        jTable1.setEnabled(test);
        btnValid.setEnabled(test);
        for (Component cp : jPanel4.getComponents()) {
            cp.setEnabled(test);
        }
    }

    void fillForm(entity.Commande c) {
        if (c == null) {
            return;
        }
        txtRef.setText(c.getRef());
        txtBenefice.setValue(c.getBenefice());
        txtCredit.setValue(c.getCredit());
        txtTotal.setValue(c.getTotal());
        txtsomme.setValue(c.getSommePaye());
        cmbClient.setSelectedItem(c.getClientId());
        if (c.getLignCmdCollection() != null) {
            DefaultTableModel model = ((DefaultTableModel) jTable1.getModel());
            for (LignCmd l : c.getLignCmdCollection()) {
                model.addRow(new Object[]{l.getProduit().getLibelle(), l.getProduit(), l.getProduit().getPrixVendre(), l.getQte(),
                    l.getHauteur(), l.getLargeur(), l.getTotal(), l.getMarge()});
            }
        }
    }

    void createJtable() {
        Object[][] rowData = {};
        Object[] columnNames = {"produit_id", "id_pdt", "prix_vendu", "qte", "hauteur", "largeur", "total", "marge"};

        DefaultTableModel listTableModel;
        listTableModel = new DefaultTableModel(rowData, columnNames);
        jTable1.setModel(listTableModel);
        jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        //Set header text
        jTable1.getColumn("produit_id").setHeaderValue("Produit");
        jTable1.getColumn("prix_vendu").setHeaderValue("Prix");
        jTable1.getColumn("qte").setHeaderValue("Quantitée");
        jTable1.getColumn("hauteur").setHeaderValue("Hauteur");
        jTable1.getColumn("largeur").setHeaderValue("Largeur");
        jTable1.getColumn("marge").setHeaderValue("La marge");
        jTable1.getColumn("total").setHeaderValue("Total");
        //jTable1.getColumn("produit_id_or").setHeaderValue("");
        // update some features.
        jTable1.getColumn("id_pdt").setMaxWidth(0);
        jTable1.getColumn("id_pdt").setMinWidth(0);
        jTable1.getColumn("id_pdt").setPreferredWidth(0);
//        jTable1.setRowSelectionAllowed(true);
//        jTable1.setCellSelectionEnabled(true);
        //set
    }

    boolean validForm() {
        boolean b;
        b = true;
        if (cmbClient.getSelectedIndex() == -1) {
            cmbClient.setBorder(BorderFactory.createLineBorder(Color.RED));
            lblclt.setForeground(Color.RED);
            b = false;
        } else {
            cmbClient.setBorder(BorderFactory.createEtchedBorder());
            lblclt.setForeground(Color.BLACK);
        }
        if (txtTotal.getText().isEmpty()) {
            txtTotal.setBorder(BorderFactory.createLineBorder(Color.RED));
            lbltotal.setForeground(Color.RED);
            b = false;
        } else {
            txtTotal.setBorder(BorderFactory.createEtchedBorder());
            lbltotal.setForeground(Color.BLACK);
        }
        if (!b) {
            lblMsg1.setText("Veuillez remplir les champs obligatoires");
            lblMsg1.setVisible(true);
            return false;
        } else {
            lblMsg1.setVisible(false);
        }
        double som = 0.0, total = 0.0;
        if (!txtsomme.getText().isEmpty()) {
            som = Double.parseDouble(txtsomme.getText().replace(',', '.'));
        }
        if (!txtTotal.getText().isEmpty()) {
            total = Double.parseDouble(txtTotal.getText().replace(',', '.'));
        }
        if ((total - som) < 0) {
            txtsomme.setBorder(BorderFactory.createLineBorder(Color.RED));
            lblsom.setForeground(Color.RED);
            lblMsg1.setVisible(true);
            lblMsg1.setText("La somme à payer invalid !");
            return false;
        } else {
            lblMsg1.setVisible(false);
            txtsomme.setBorder(BorderFactory.createEtchedBorder());
            lblsom.setForeground(Color.BLACK);
        }
        return true;
    }

    boolean validFormLignCmd() {
        boolean isInvalid = true;
        boolean isNotEmpty = true;
        if (txtQte.getText().trim().isEmpty()) {
            txtQte.setBorder(BorderFactory.createLineBorder(Color.RED));
            lblQte.setForeground(Color.RED);
            isNotEmpty = false;
        } else {
            try {
                Integer.parseInt(txtQte.getText());
                txtQte.setBorder(BorderFactory.createBevelBorder(1));
                lblQte.setForeground(Color.BLACK);
            } catch (Exception ex) {
                txtQte.setBorder(BorderFactory.createLineBorder(Color.RED));
                lblQte.setForeground(Color.RED);
                isInvalid = false;
            }
        }
        if (txtPrix.getText().trim().isEmpty()) {
            txtPrix.setBorder(BorderFactory.createLineBorder(Color.RED));
            lblPrix.setForeground(Color.RED);
            isNotEmpty = false;
        } else {
            try {
                Double.parseDouble(txtPrix.getText());
                txtPrix.setBorder(BorderFactory.createBevelBorder(1));
                lblPrix.setForeground(Color.BLACK);
            } catch (Exception ex) {
                txtPrix.setBorder(BorderFactory.createLineBorder(Color.RED));
                lblPrix.setForeground(Color.RED);
                isInvalid = false;
            }
        }        
        if (cmbPdt.getSelectedIndex() == -1) {
            cmbPdt.setBorder(BorderFactory.createLineBorder(Color.RED));
            lblpdt.setForeground(Color.RED);
            isNotEmpty = false;
        } else {
            cmbPdt.setBorder(BorderFactory.createEtchedBorder());
            lblpdt.setForeground(Color.BLACK);
        }

        boolean temp;
        if (!isNotEmpty) {
            temp = isNotEmpty;
            lblMsg.setText("Veuillez remplir les champs obligatoires");
        } else {
            temp = isInvalid;
            lblMsg.setText("Les information saisi sont incorrecte");
        }
        lblMsg.setVisible(!temp);
        return temp;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        gestionPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("gestionPU").createEntityManager();
        clientQuery = java.beans.Beans.isDesignTime() ? null : gestionPUEntityManager.createQuery("SELECT c FROM Client c");
        clientList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientQuery.getResultList();
        produitQuery = java.beans.Beans.isDesignTime() ? null : gestionPUEntityManager.createQuery("SELECT p FROM Produit p");
        produitList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : produitQuery.getResultList();
        jPanel2 = new javax.swing.JPanel();
        lblclt = new javax.swing.JLabel();
        refLabel = new javax.swing.JLabel();
        txtRef = new javax.swing.JTextField();
        dateCmdLabel = new javax.swing.JLabel();
        jdate = new javax.swing.JSpinner();
        cmbClient = new javax.swing.JComboBox();
        produitListCellRenderer1 = new presentation.ProduitListCellRenderer();
        jPanel4 = new javax.swing.JPanel();
        cmbPdt = new javax.swing.JComboBox();
        lblpdt = new javax.swing.JLabel();
        txtHauteur = new javax.swing.JTextField();
        txtLargeur = new javax.swing.JTextField();
        txtQte = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblQte = new javax.swing.JLabel();
        btnValid = new javax.swing.JButton();
        btnValid1 = new javax.swing.JButton();
        lblMsg = new javax.swing.JLabel();
        btnValid3 = new javax.swing.JButton();
        txtPrix = new javax.swing.JTextField();
        lblPrix = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        lbltotal = new javax.swing.JLabel();
        lblsom = new javax.swing.JLabel();
        creditLabel = new javax.swing.JLabel();
        beneficeLabel = new javax.swing.JLabel();
        txtTotal = new javax.swing.JFormattedTextField();
        txtsomme = new javax.swing.JFormattedTextField();
        txtBenefice = new javax.swing.JFormattedTextField();
        txtCredit = new javax.swing.JFormattedTextField();
        deleteButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        lblMsg1 = new javax.swing.JLabel();

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Information sur la commande"));

        lblclt.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblclt.setText("Client: ");

        refLabel.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        refLabel.setText("Ref:");

        txtRef.setEditable(false);
        txtRef.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${currentCommande.ref}"), txtRef, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        dateCmdLabel.setText("Date  de création: ");

        jdate.setModel(new javax.swing.SpinnerDateModel());
        jdate.setEditor(new javax.swing.JSpinner.DateEditor(jdate, "dd/MM/yyyy"));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${currentCommande.dateCmd}"), jdate, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        cmbClient.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cmbClient.setRenderer(produitListCellRenderer1);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, clientList, cmbClient);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${currentCommande.clientId}"), cmbClient, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cmbClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbClientActionPerformed(evt);
            }
        });

        produitListCellRenderer1.setText("produitListCellRenderer1");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(dateCmdLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(163, 163, 163)
                        .addComponent(produitListCellRenderer1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(refLabel)
                        .addGap(20, 20, 20)
                        .addComponent(txtRef, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblclt)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbClient, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(refLabel)
                    .addComponent(txtRef, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblclt)
                    .addComponent(cmbClient, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dateCmdLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(produitListCellRenderer1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Lignes commande"));

        cmbPdt.setName("cmbClient"); // NOI18N
        cmbPdt.setRenderer(produitListCellRenderer1);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, produitList, cmbPdt);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTable1, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.produit}"), cmbPdt, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cmbPdt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbPdtActionPerformed(evt);
            }
        });
        cmbPdt.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                cmbPdtPropertyChange(evt);
            }
        });

        lblpdt.setText("Produit: ");

        txtHauteur.setName("txtHauteur"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTable1, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.hauteur}"), txtHauteur, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtHauteur.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtHauteurActionPerformed(evt);
            }
        });
        txtHauteur.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtHauteurKeyTyped(evt);
            }
        });

        txtLargeur.setName("txtLargeur"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTable1, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.largeur}"), txtLargeur, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        txtQte.setName("txtQte"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTable1, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.qte}"), txtQte, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel1.setText("Hauteur");

        jLabel2.setText("Largeur");

        lblQte.setText("Quantité");

        btnValid.setText("Nouveau");
        btnValid.setName("txtValider"); // NOI18N
        btnValid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnValidActionPerformed(evt);
            }
        });

        btnValid1.setText("Valider");
        btnValid1.setName("txtValider"); // NOI18N
        btnValid1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnValid1ActionPerformed(evt);
            }
        });

        lblMsg.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
        lblMsg.setForeground(new java.awt.Color(255, 0, 0));
        lblMsg.setText("Veuillez remplir les champs obligatoires");
        lblMsg.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        btnValid3.setText("Supp.");
        btnValid3.setName("txtValider"); // NOI18N
        btnValid3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnValid3ActionPerformed(evt);
            }
        });

        txtPrix.setName("txtQte"); // NOI18N

        lblPrix.setText("Prix");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblpdt)
                                    .addComponent(jLabel1))
                                .addComponent(jLabel2))
                            .addComponent(lblQte))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cmbPdt, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(btnValid1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(txtLargeur, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtHauteur, javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup()
                                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(btnValid, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(jPanel4Layout.createSequentialGroup()
                                            .addComponent(txtQte, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(lblPrix)))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(btnValid3, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE)
                                        .addComponent(txtPrix)))))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(lblMsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblMsg)
                .addGap(14, 14, 14)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblpdt)
                    .addComponent(cmbPdt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtHauteur, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtLargeur, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblQte)
                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                        .addComponent(lblPrix)
                        .addComponent(txtPrix, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtQte, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnValid)
                    .addComponent(btnValid3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnValid1))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Réglement: "));

        lbltotal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lbltotal.setText("Total:");

        lblsom.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblsom.setText("Somme Paye:");

        creditLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        creditLabel.setText("Credit:");

        beneficeLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        beneficeLabel.setText("Benefice:");

        txtTotal.setEditable(false);
        txtTotal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        txtTotal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${currentCommande.total}"), txtTotal, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        txtsomme.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        txtsomme.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${currentCommande.sommePaye}"), txtsomme, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        txtsomme.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                txtsommePropertyChange(evt);
            }
        });

        txtBenefice.setEditable(false);
        txtBenefice.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        txtBenefice.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${currentCommande.benefice}"), txtBenefice, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        txtCredit.setEditable(false);
        txtCredit.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        txtCredit.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${currentCommande.credit}"), txtCredit, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        deleteButton1.setText("Valider");
        deleteButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(deleteButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbltotal)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblsom)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtsomme, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(beneficeLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtBenefice, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(creditLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtCredit, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(creditLabel)
                        .addComponent(txtCredit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(beneficeLabel)
                        .addComponent(lbltotal)
                        .addComponent(lblsom)
                        .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtsomme, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtBenefice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addComponent(deleteButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${currentCommande.lignCmdCollection}");
        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${produit}"));
        columnBinding.setColumnName("Produit");
        columnBinding.setColumnClass(entity.Produit.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${prixVendu}"));
        columnBinding.setColumnName("Prix Vendu");
        columnBinding.setColumnClass(Double.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${qte}"));
        columnBinding.setColumnName("Qte");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${hauteur}"));
        columnBinding.setColumnName("Hauteur");
        columnBinding.setColumnClass(Double.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${largeur}"));
        columnBinding.setColumnName("Largeur");
        columnBinding.setColumnClass(Double.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${total}"));
        columnBinding.setColumnName("Total");
        columnBinding.setColumnClass(Double.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${marge}"));
        columnBinding.setColumnName("Marge");
        columnBinding.setColumnClass(Double.class);
        jTableBinding.setSourceNullValue(new LinkedList<LignCmd>()
        );
        jTableBinding.setSourceUnreadableValue(java.util.Collections.emptyList());
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setMinWidth(0);
            jTable1.getColumnModel().getColumn(0).setPreferredWidth(0);
            jTable1.getColumnModel().getColumn(0).setMaxWidth(0);
        }

        lblMsg1.setFont(new java.awt.Font("Tahoma", 3, 11)); // NOI18N
        lblMsg1.setForeground(new java.awt.Color(255, 0, 0));
        lblMsg1.setText("Veuillez remplir les champs obligatoires");
        lblMsg1.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lblMsg1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(298, 298, 298))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(6, 6, 6))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(10, 10, 10)
                                .addComponent(jScrollPane1)))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(lblMsg1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(48, 48, 48))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void cmbClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbClientActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbClientActionPerformed

    private void cmbPdtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbPdtActionPerformed
        // TODO add your handling code here:
        if( cmbPdt.getSelectedIndex() != -1 )
            txtPrix.setText(((entity.Produit)cmbPdt.getSelectedItem()).getPrixVendre().toString());
        else
            txtPrix.setText("");
    }//GEN-LAST:event_cmbPdtActionPerformed

    private void txtHauteurActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtHauteurActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtHauteurActionPerformed

    private void txtHauteurKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtHauteurKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_txtHauteurKeyTyped

    private void btnValidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValidActionPerformed
        jTable1.clearSelection();
        emptyField();

    }//GEN-LAST:event_btnValidActionPerformed

    void emptyField() {
        txtHauteur.setText("");
        txtLargeur.setText("");
        txtQte.setText("");
        cmbPdt.setSelectedIndex(-1);

    }
    private void btnValid1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValid1ActionPerformed

        if (cmbPdt.getSelectedIndex() != -1) {
            if (!txtLargeur.getText().trim().isEmpty() && !txtHauteur.getText().trim().isEmpty()) {
                double suf = Double.parseDouble(txtLargeur.getText()) * Double.parseDouble(txtHauteur.getText());
                int qte = (int) ((1 - ((suf * PARPA) - ((int) (suf * PARPA)))) + (suf * PARPA));
                txtQte.setText(String.valueOf(qte));
            } else if (!txtLargeur.getText().trim().isEmpty()) {
                int qte = (int) ((1 - ((Double.parseDouble(txtLargeur.getText()) * LOURDI) - ((int) (Double.parseDouble(txtLargeur.getText()) * LOURDI)))) + (Double.parseDouble(txtLargeur.getText()) * LOURDI));
                txtQte.setText(String.valueOf(qte));
            }
        }
        if (!validFormLignCmd()) {
            return;
        }
        if (existe()) {
            JOptionPane.showMessageDialog(this, "Le produit est existe déjà");
            return;
        }
        if (jTable1.getSelectedRow() == -1) {
            ((DefaultTableModel) jTable1.getModel()).addRow(new Object[]{((entity.Produit) cmbPdt.getSelectedItem()).getLibelle(),
                ((entity.Produit) cmbPdt.getSelectedItem()),
                txtPrix.getText(),
                txtQte.getText(),
                txtHauteur.getText(),
                txtLargeur.getText(),
                Double.parseDouble(txtPrix.getText()) * Integer.parseInt(txtQte.getText()),
                (Double.parseDouble(txtPrix.getText()) - ((entity.Produit) cmbPdt.getSelectedItem()).getPrixAchat()) * Integer.parseInt(txtQte.getText())
            });
//            int row = jTable1.getRowCount() - 1;
//            jTable1.setRowSelectionInterval(row, row);
//            jTable1.scrollRectToVisible(jTable1.getCellRect(row, 0, true));
            //jTable1.clearSelection();
        } else {
            jTable1.setValueAt(((entity.Produit) cmbPdt.getSelectedItem()).getLibelle(), jTable1.getSelectedRow(), 0);
            jTable1.setValueAt(((entity.Produit) cmbPdt.getSelectedItem()), jTable1.getSelectedRow(), 1);
            jTable1.setValueAt(txtPrix.getText(), jTable1.getSelectedRow(), 2);
            jTable1.setValueAt(txtQte.getText(), jTable1.getSelectedRow(), 3);
            jTable1.setValueAt(txtHauteur.getText(), jTable1.getSelectedRow(), 4);
            jTable1.setValueAt(txtLargeur.getText(), jTable1.getSelectedRow(), 5);
            jTable1.setValueAt(Double.parseDouble(txtPrix.getText()) * Integer.parseInt(txtQte.getText()), jTable1.getSelectedRow(), 6);
            jTable1.setValueAt((Double.parseDouble(txtPrix.getText()) - ((entity.Produit) cmbPdt.getSelectedItem()).getPrixAchat()) * Integer.parseInt(txtQte.getText()), jTable1.getSelectedRow(), 7);
//            ((DefaultTableModel) jTable1.getModel()).insertRow(jTable1.getSelectedRow(), new Object[]{((entity.Produit) cmbPdt.getSelectedItem()).getLibelle(),
//                ((entity.Produit) cmbPdt.getSelectedItem()),
//                ((entity.Produit) cmbPdt.getSelectedItem()).getPrixVendre(),
//                txtQte.getText(),
//                txtHauteur.getText(),
//                txtLargeur.getText(),
//                ((entity.Produit) cmbPdt.getSelectedItem()).getPrixVendre() * Integer.parseInt(txtQte.getText()),
//                (((entity.Produit) cmbPdt.getSelectedItem()).getPrixVendre() - ((entity.Produit) cmbPdt.getSelectedItem()).getPrixAchat()) * Integer.parseInt(txtQte.getText())
//            });
//            ((DefaultTableModel) jTable1.getModel()).removeRow(jTable1.getSelectedRow());
        }
        jTable1.clearSelection();
        emptyField();
        calcTotal();
        calcCredit();
    }//GEN-LAST:event_btnValid1ActionPerformed

    private void deleteButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButton1ActionPerformed
        // TODO add your handling code here:

        if (validForm()) {
            this.currentCommande.setBenefice(Double.parseDouble(txtBenefice.getText().replace(',', '.')));
            this.currentCommande.setClientId((entity.Client) cmbClient.getSelectedItem());
            this.currentCommande.setCredit(Double.parseDouble(txtCredit.getText().replace(',', '.')));
            this.currentCommande.setDateCmd((Date) jdate.getValue());
            this.currentCommande.setSommePaye(Double.parseDouble(txtsomme.getText().isEmpty() ? "0.0" : txtsomme.getText().replace(',', '.')));
            this.currentCommande.setTotal(Double.parseDouble(txtTotal.getText().replace(',', '.')));
//            this.currentCommande.setLignCmdCollection(getList());

            if (currentCommande.getId() == null) {
                gestionPUEntityManager.persist(this.currentCommande);
                gestionPUEntityManager.getTransaction().commit();
                currentCommande.setRef("CMD-" + currentCommande.getId());
                txtRef.setText("CMD-" + currentCommande.getId());
                gestionPUEntityManager.getTransaction().begin();
                this.currentCommande.setLignCmdCollection(getList());
            }

            gestionPUEntityManager.getTransaction().commit();

            JOptionPane.showMessageDialog(this, "L'operation est terminé avec succée ");
//            setVisible(true);
//            JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);
            
        }
    }//GEN-LAST:event_deleteButton1ActionPerformed

    List<LignCmd> getList() {
        DefaultTableModel model = ((DefaultTableModel) jTable1.getModel());
        LignCmd l;
        List<LignCmd> ls = new LinkedList<>();
        for (int i = 0; i < model.getRowCount(); i++) {
            l = new LignCmd();
            l.setCommande(currentCommande);
            System.out.println(currentCommande.getId());
            System.out.println(((entity.Produit) model.getValueAt(i, 1)).getId());
            l.setLignCmdPK(new LignCmdPK(currentCommande.getId(), ((entity.Produit) model.getValueAt(i, 1)).getId(), new Short("1")));
            l.setHauteur(model.getValueAt(i, 4).toString().isEmpty() ? 0.0 : Double.parseDouble(model.getValueAt(i, 4).toString().toString()));
            l.setLargeur(model.getValueAt(i, 5).toString().isEmpty() ? 0.0 : Double.parseDouble(model.getValueAt(i, 5).toString()));
            l.setMarge(model.getValueAt(i, 7).toString().isEmpty() ? 0.0 : Double.parseDouble(model.getValueAt(i, 7).toString()));
            l.setPrixVendu(model.getValueAt(i, 2).toString().isEmpty() ? 0.0 : Double.parseDouble(model.getValueAt(i, 2).toString()));
            l.setProduit((entity.Produit) model.getValueAt(i, 1));
            l.setQte(model.getValueAt(i, 3).toString().isEmpty() ? 0 : Integer.parseInt(model.getValueAt(i, 3).toString()));
            l.setTotal(model.getValueAt(i, 6).toString().isEmpty() ? 0.0 : Double.parseDouble(model.getValueAt(i, 6).toString()));
            ls.add(l);
        }

        return ls;
    }
    private void btnValid3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnValid3ActionPerformed
        // TODO add your handling code here:
        if (jTable1.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "Veuillez selectionner une ligne ");
        } else {
            if (JOptionPane.showConfirmDialog(this, "Voulez-vous vrêment supprimer cette ligne ?", "Confirmation !", 0) == 0) {
                ((DefaultTableModel) jTable1.getModel()).removeRow(jTable1.getSelectedRow());
                jTable1.clearSelection();
            }
        }
        calcTotal();
    }//GEN-LAST:event_btnValid3ActionPerformed

    boolean existe() {
        DefaultTableModel model = ((DefaultTableModel) jTable1.getModel());
        for (int i = 0; i < model.getRowCount(); i++) {
            if (i == jTable1.getSelectedRow()) {
                continue;
            }
            if (((entity.Produit) model.getValueAt(i, 1)).equals(cmbPdt.getSelectedItem())) {
                return true;
            }
        }
        return false;
    }
    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:

        //JOptionPane.showMessageDialog(this, jTable1.getSelectedRow());
        if (jTable1.getSelectedRow() != -1) {
            txtQte.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 3).toString());
            txtHauteur.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 4).toString());
            txtLargeur.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 5).toString());
            cmbPdt.setSelectedItem((entity.Produit) jTable1.getValueAt(jTable1.getSelectedRow(), 1));
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void txtsommePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_txtsommePropertyChange
        // TODO add your handling code here:
        if (evt.getPropertyName().equals("value")) {
            calcCredit();
        }
    }//GEN-LAST:event_txtsommePropertyChange

    private void cmbPdtPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_cmbPdtPropertyChange
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbPdtPropertyChange

    void calcTotal() {
        double[] res = {0.0, 0.0};
        DefaultTableModel model = ((DefaultTableModel) jTable1.getModel());
        for (int i = 0; i < model.getRowCount(); i++) {
            if (model.getValueAt(i, 6) != null) {
                res[0] += (double) model.getValueAt(i, 6);
            }
            if (model.getValueAt(i, 7) != null) {
                res[1] += (double) model.getValueAt(i, 7);
            }
        }
        txtTotal.setValue((double) res[0]);
        txtBenefice.setValue((double) res[1]);
    }

    void calcCredit() {
        double som = 0.0, total = 0.0;
        if (!txtsomme.getText().isEmpty()) {
            som = Double.parseDouble(txtsomme.getText().replace(',', '.'));
        }
        if (!txtTotal.getText().isEmpty()) {
            total = Double.parseDouble(txtTotal.getText().replace(',', '.'));
        }
        txtCredit.setValue((total - som));
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel beneficeLabel;
    private javax.swing.JButton btnValid;
    private javax.swing.JButton btnValid1;
    private javax.swing.JButton btnValid3;
    private java.util.List<entity.Client> clientList;
    private javax.persistence.Query clientQuery;
    private javax.swing.JComboBox cmbClient;
    private javax.swing.JComboBox cmbPdt;
    private javax.swing.JLabel creditLabel;
    private javax.swing.JLabel dateCmdLabel;
    private javax.swing.JButton deleteButton1;
    private javax.persistence.EntityManager gestionPUEntityManager;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JSpinner jdate;
    private javax.swing.JLabel lblMsg;
    private javax.swing.JLabel lblMsg1;
    private javax.swing.JLabel lblPrix;
    private javax.swing.JLabel lblQte;
    private javax.swing.JLabel lblclt;
    private javax.swing.JLabel lblpdt;
    private javax.swing.JLabel lblsom;
    private javax.swing.JLabel lbltotal;
    private java.util.List<entity.Produit> produitList;
    private presentation.ProduitListCellRenderer produitListCellRenderer1;
    private javax.persistence.Query produitQuery;
    private javax.swing.JLabel refLabel;
    private javax.swing.JFormattedTextField txtBenefice;
    private javax.swing.JFormattedTextField txtCredit;
    private javax.swing.JTextField txtHauteur;
    private javax.swing.JTextField txtLargeur;
    private javax.swing.JTextField txtPrix;
    private javax.swing.JTextField txtQte;
    private javax.swing.JTextField txtRef;
    private javax.swing.JFormattedTextField txtTotal;
    private javax.swing.JFormattedTextField txtsomme;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the currentCommande
     */
    public entity.Commande getCurrentCommande() {
        return currentCommande;
    }

    /**
     * @param currentCommande the currentCommande to set
     */
    public void setCurrentCommande(entity.Commande currentCommande) {
        this.currentCommande = currentCommande;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CommandeDetailForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CommandeDetailForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CommandeDetailForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CommandeDetailForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new CommandeDetailForm(null));
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
